<template>
  <div id="users">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="7">
          <!-- 搜索与添加区域 -->
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="queryInfo.query"
            clearable
            @clear="get_users_list"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="get_users_list"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="add_dialog_visible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 用户表格区域 -->
      <el-table :data="user_list" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="user_state_changed(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <!-- 修改按钮 -->
          <template slot-scope="scope">
            <el-button
              @click="eidt_dialog_visible_btn(scope.row.id)"
              type="primary"
              icon="el-icon-edit"
              size="mini"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="del_dialog_visible_btn(scope.row.id)"
            ></el-button>
            <!-- 设置按钮 -->
            <el-tooltip content="分配角色" placement="top" :enterable="false">
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="set_user_visible(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户对话框区域 -->
    <el-dialog
      title="提示"
      :visible.sync="add_dialog_visible"
      width="50%"
      @close="add_dialog_close"
    >
      <!-- 弹出框内容区域 -->
      <el-form
        :model="add_form"
        :rules="add_form_rules"
        ref="add_form_ref"
        label-width="80px"
      >
        <!-- 用户名输入框 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="add_form.username"></el-input>
        </el-form-item>
        <!-- 密码输入框 -->
        <el-form-item label="密码" prop="password">
          <el-input v-model="add_form.password"></el-input>
        </el-form-item>
        <!-- 邮箱输入框 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="add_form.email"></el-input>
        </el-form-item>
        <!-- 手机号输入框 -->
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="add_form.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="add_dialog_visible = false">取 消</el-button>
        <el-button type="primary" @click="add_user">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="eidt_dialog_visible"
      width="50%"
      @close="eidt_dialog_close"
    >
      <el-form
        :model="eidt_form"
        :rules="add_form_rules"
        ref="eidt_form_ref"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input v-model="eidt_form.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="eidt_form.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="eidt_form.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="eidt_dialog_visible = false">取 消</el-button>
        <el-button type="primary" @click="eidt_user_info">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog title="提示" :visible.sync="set_role_dialog_visible" width="50%" @close="set_role_dialog_close">
      <div>
        <p>当前的用户：{{ user_info.username }}</p>
        <p>当前的角色：{{ user_info.role_name }}</p>
        <p>分配新角色：
          <el-select v-model="select_role_id" placeholder="请选择">
            <el-option
              v-for="item in roles_list"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="set_role_dialog_visible = false">取 消</el-button>
        <el-button type="primary" @click="save_role_info"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    // 邮箱验证规则
    var check_email = (rule, value, cb) => {
      let reg_email = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
      if (reg_email.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的邮箱"));
    };
    // 手机号验证规则
    var check_mobile = (rule, value, cb) => {
      let reg_mobile = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;
      if (reg_mobile.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的手机号"));
    };
    return {
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      user_list: [],
      total: 0,
      // 隐藏添加用户对话框
      add_dialog_visible: false,
      // 添加用户的表单数据
      add_form: {
        usrename: "",
        password: "",
        email: "",
        mobile: "",
      },
      // 添加用户的表单验证对象
      add_form_rules: {
        username: [
          { required: true, message: "请输入用戶名", tigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "用户名的长度应在3-10个字符之间",
            tigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", tigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "密码的长度应在6-15个字符之间",
            tigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", tigger: "blur" },
          { validator: check_email, tigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", tigger: "blur" },
          { validator: check_mobile, tigger: "blur" },
        ],
      },
      // 隐藏修改用户对话框
      eidt_dialog_visible: false,
      // 查询到的用户信息
      eidt_form: {},
      // 控制分配角色信息对话框的显示与隐藏
      set_role_dialog_visible: false,
      // 需要被分配角色的信息
      user_info: {},
      // 所有角色的数据列表
      roles_list: [],
      // 已选中的id 值
      select_role_id: "",
    };
  },
  created() {
    this.get_users_list();
  },
  methods: {
    // 获取所有用户信息
    async get_users_list() {
      let { data: res } = await this.axios.get("users", {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200) {
        return this.message.error("获取用户信息失败");
      }
      this.user_list = res.data.users;
      this.total = res.data.total;
    },
    // 监听 pagesize 值的改变
    handleSizeChange(new_size) {
      this.queryInfo.pagesize = new_size;
      this.get_users_list();
    },
    // 监听 页码值 的改变
    handleCurrentChange(page_num) {
      this.queryInfo.pagenum = page_num;
      this.get_users_list();
    },
    // 监听switch开关状态的改变
    async user_state_changed(user_info) {
      console.log(user_info);
      let { data: res } = await this.axios.put(
        `users/${user_info.id}/state/${user_info.mg_state}`
      );
      if (res.meta.status !== 200) {
        user_info.mg_state = !user_info.mg_state;
        this.message.error("更新用户信息失败");
      }
      this.message.success("更新用户信息成功！");
    },
    // 监听添加用户对话框关闭
    add_dialog_close() {
      this.$refs.add_form_ref.resetFields();
    },
    // 点击按钮，添加用户
    add_user() {
      this.$refs.add_form_ref.validate(async (valid) => {
        if (!valid) return;
        console.log(valid);
        // 可以发起添加用户的网络请求
        let { data: res } = await this.axios.post("users", this.add_form);
        if (res.meta.status !== 201) {
          return this.message.error("添加用户失败！");
        }
        this.message.success("添加用户成功！");
        // 隐藏添加用户的对话框
        this.add_dialog_visible = false;
        this.get_users_list();
      });
    },
    // 点击按钮，修改用户
    async eidt_dialog_visible_btn(id) {
      let { data: res } = await this.axios.get("users/" + id);
      if (res.meta.status !== 200) {
        return this.message.error("获取用户信息失败");
      }
      this.eidt_form = res.data;
      console.log(this.eidt_form.id);
      this.eidt_dialog_visible = true;
    },
    // 监听修改用户对话框关闭事件
    eidt_dialog_close() {
      this.$refs.eidt_form_ref.resetFields();
    },
    // 修改用户信息并提交
    eidt_user_info() {
      this.$refs.eidt_form_ref.validate(async (valid) => {
        if (!valid) return;
        // 发起修改用户信息的请求
        let { data: res } = await this.axios.put("users/" + this.eidt_form.id, {
          email: this.eidt_form.email,
          mobile: this.eidt_form.mobile,
        });
        if (res.meta.status !== 200) {
          return this.message.error("更改用户信息失败");
        }
        // 关闭对话框
        this.eidt_dialog_visible = false;
        // 提示更改成功
        this.message.success("更改用户信息成功");
        // 重新获取数据
        this.get_users_list();
      });
    },
    // 点击按钮，删除用户
    async del_dialog_visible_btn(id) {
      let confirm_result = await this.confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      // 点击确定，返回confirm
      // 点击取消，返回cancel
      if (confirm_result !== "confirm") {
        return this.message.info("已取消删除");
      }
      let { data: res } = await this.axios.delete("users/" + id);

      if (res.meta.status !== 200) {
        return this.message.error("删除用户失败");
      }
      this.message.success("删除用户成功");
      this.get_users_list();
    },
    // 点击按钮，展示分配角色对话框
    async set_user_visible(user_info) {
      this.user_info = user_info;
      // 展示对话框之前，获取所有角色信息
      let { data: res } = await this.axios("roles");
      if (res.meta.status !== 200) {
        return thsi.message.error("获取角色信息失败");
      }
      this.roles_list = res.data;
      console.log(res.data)
      this.set_role_dialog_visible = true;
    },
    // 点击按钮分配角色
    async save_role_info(){
      if(!this.select_role_id){
        return this.message.error("请选择要分配的角色")
      }
      let {data: res} = await this.axios.put(`users/${this.user_info.id}/role`,{
        rid: this.select_role_id
      })
      if(res.meta.status !== 200){
        return this.message.error("更新角色失败")
      }
      this.message.success("更新角色成功")
      this.get_users_list()
      this.set_role_dialog_visible = false
    },
    // 监听分配角色对话框关闭，清空对话框中的值
    set_role_dialog_close(){
      this.select_role_id = "";
      this.user_info = {}
    }
  },
};
</script>
<style lang="less" scoped>
.el-table {
  margin-top: 15px;
  font-size: 12px;
}
</style>